package com.szpx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szpx.entity.UserInfo;
import com.szpx.mapper.UserInfoMapper;
import com.szpx.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Hudson
 * @Version: 1.0
 * @Date: 2024/4/3 12:15
 * @Description: TODO
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Override
	public List<UserInfo> findAll() {
		return userInfoMapper.selectAll();
	}
	
	@Override
	public UserInfo findById(Integer id) {
		return userInfoMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void addUserInfo(UserInfo userInfo) {
		// 获取当前时间
		LocalDateTime currentDateTime = LocalDateTime.now();
		userInfo.setRegistrationDate(currentDateTime);
		userInfoMapper.insert(userInfo);
	}
	
	@Override
	public void updateUserInfo(UserInfo userInfo) {
		userInfoMapper.updateByPrimaryKey(userInfo);
	}
	
	@Override
	public void deleteUserInfo(Integer id) {
		userInfoMapper.deleteByPrimaryKey(id);
	}
	
	/**
	 * 构建用户查询对象
	 *
	 * @param userInfo
	 * @return
	 */
	public Example creatExample(UserInfo userInfo) {
		Example example = new Example(UserInfo.class);
		Example.Criteria criteria = example.createCriteria();
		if (userInfo != null) {
//			//用户id
//			if (!StringUtils.isEmpty(userInfo.getId())) {
//				criteria.andEqualTo("id", userInfo.getId());
//			}
			//用户名称
			if (!StringUtils.isEmpty(userInfo.getName())) {
				criteria.andLike("name", "%" + userInfo.getName() + "%");
			}
			//用户性别
			if (!StringUtils.isEmpty(userInfo.getSex())) {
				criteria.andEqualTo("sex", userInfo.getSex());
			}
//			//用户年龄
//			if (!StringUtils.isEmpty(userInfo.getAge())) {
//				criteria.andEqualTo("age", userInfo.getAge());
//			}
		}
		return example;
	}
	
	/**
	 * 多条件查询
	 *
	 * @param userInfo
	 * @return
	 */
	@Override
	public List<UserInfo> findList(UserInfo userInfo) {
		//构建查询条件
		Example example = creatExample(userInfo);
		//根据构建的条件查询数据
		return userInfoMapper.selectByExample(example);
	}
	
	/**
	 * 分页查询结果
	 *
	 * @param page
	 * @param size
	 * @return
	 */
	@Override
	public PageInfo<UserInfo> findPage(int page, int size) {
		//静态分页
		PageHelper.startPage(page, size);
		//分页查询
		return new PageInfo<UserInfo>(userInfoMapper.selectAll());
	}
	
	/**
	 * UserInfo条件+分页查询
	 *
	 * @param userInfo
	 * @param page
	 * @param size
	 * @return 分页结果
	 */
	@Override
	public PageInfo<UserInfo> findPage(UserInfo userInfo, int page, int size) {
		//静态分页
		PageHelper.startPage(page, size);
		//构建查询条件
		Example example = creatExample(userInfo);
		//根据构建的条件查询数据，分页查询
		return new PageInfo<UserInfo>(userInfoMapper.selectByExample(example));
	}
}
